﻿using Knight.Web.Infrastructure;

using Knight.Common;
using Knight.Models.Entity;
using Knight.Models.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Knlght.Domain;

namespace WebApp.Areas.Manage.Controllers
{
    public class AccountController : BaseController
    {
        /// <summary>
        /// 登录界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            ViewBag.PublicKey = RSACrypto.PublicKey;
            return View();
        }

        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="verifycode"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CheckLogin(string username, string password, string verifycode)
        {

            var rsaCrypto = new RSACrypto();
            //解密 RSA
            username = rsaCrypto.Decrypt(username);
            password = rsaCrypto.Decrypt(password);
            var response = new ItemResponse<Administrators>();
            var logInfo = new LogInfo
            {
                ModuleName = "系统登录",
                TypeName = DbLogType.Login.ToString()
            };
            var error = "";
            var id = "";
            //验证码验证
            var cookieVerifyCode = CookieHelper.Get("verifyCode");
            if (cookieVerifyCode == null)
            {
                error = "验证码已过期！";
            }
            else
            {
                if (!string.Equals(verifycode.Trim(), cookieVerifyCode.Value, StringComparison.CurrentCultureIgnoreCase))
                {
                    error = "验证码错误!";
                }
                else
                {
                var service = new AdministratorsService();
                response = service.CheckLogin(username, password);
                if (!response.IsSuccess)
                {
                    error = response.Message;
                }
                else
                {
                    id = response.Model.Id;
                }

                }
            }
            if (string.IsNullOrEmpty(error))
            {
                //验证成功
                var cacheTime = 300;
                #region 发放登录凭证
                var ticket = new FormsAuthenticationTicket(1,
                   id,
                   DateTime.Now,
                   DateTime.Now.AddMinutes(cacheTime),
                   true,
                   "admin");

                var enString = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName) { Value = enString };
                Response.SetCookie(cookie);
                //验证是否为超级管理员，是就显示性能测试
                if (response.Model.IsSuper)
                {
                    var cookie2 = new HttpCookie(FormsAuthentication.FormsCookieName) { Name = "cxh", Value = "ADMIN" };
                    Response.SetCookie(cookie2);
                }

                #endregion

                var returnUrl = Request.QueryString["ReturnUrl"];
                if (string.IsNullOrEmpty(returnUrl))
                {
                    returnUrl = "/Manage/Home/Index";
                }
                logInfo.Account = response.Model.Id;
                logInfo.Username = response.Model.Username;
                logInfo.Result = true;
                logInfo.Description = "登录成功";

                #region 将对象放入缓存
                if (response.Model.IsSuper)
                {
                    response.Model.RoleName = "超级管理员";
                }
                else
                {
                    var query = new QueryRequest<RoleInfo>();
                    query.Add(o => o.IsEnabled == true);
                    var roleRsp = getDefaultService().GetList<RoleInfo>(query);
                    if (roleRsp.IsSuccess)
                    {
                        foreach (var item in roleRsp.Models)
                        {
                            if (response.Model.OwmRoleId == item.Id)
                            {
                                response.Model.RoleName = item.Name;
                            }
                        }
                    }
                }
                if (string.IsNullOrEmpty(response.Model.ImageUrl))
                {
                    response.Model.ImageUrl = "/Content/img/avatar5.png";
                }              
                CacheHelper.WriteCache(response.Model, "Admin_" + response.Model.Id, DateTime.Now.AddMinutes(cacheTime));
                #endregion

                getDefaultService().Add(logInfo);
                return Json(new { Success = true, Message = returnUrl });
            }
            else
            {
                logInfo.Account = "";
                logInfo.Username = username;
                logInfo.Result = false;
                logInfo.Description = "登录失败，" + error;
                getDefaultService().Add(logInfo);
                return Json(new { Success = false, Message = error });
            }
        }


        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Logout()
        {
            var service = getDefaultService();
            var username = service.GetModel<Administrators>(User.Identity.Name).Model.Username;
            service.Add(new LogInfo
            {
                ModuleName = "退出登录",
                TypeName = DbLogType.Exit.ToString(),
                Account = User.Identity.Name,
                Username = username,
                Result = true,
                Description = "安全退出系统",
            });
            //取消Session会话
            Session.Abandon();
            //删除Forms验证票证
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Account");
        }
    }
}